package flyweight

import "fmt"

type ImageFlayweightFactory struct {
	maps map[string]*ImageFlayweight
}

var imageFactory *ImageFlayweightFactory

func GetImageFlyweightFactory() *ImageFlayweightFactory {
	if imageFactory == nil {
		imageFactory = &ImageFlayweightFactory{
			maps: make(map[string]*ImageFlayweight),
		}
	}
	return imageFactory
}
func (f *ImageFlayweightFactory) Get(filename string) *ImageFlayweight {
	image := f.maps[filename]
	if image == nil {
		image = NewImageFlyweight(filename)
		f.maps[filename] = image
	}
	return image
}

type ImageFlayweight struct {
	data string
}

func NewImageFlyweight(filename string) *ImageFlayweight {
	data := fmt.Sprintf("image data %s", filename)
	return &ImageFlayweight{
		data: data,
	}
}
func (i *ImageFlayweight) Data() string {
	return i.data
}

type ImageViewer struct {
	*ImageFlayweight
}

func NewImageViewer(filename string) *ImageViewer {
	image := GetImageFlyweightFactory().Get(filename)
	return &ImageViewer{
		ImageFlayweight: image,
	}
}
func (i *ImageViewer) Display() {
	fmt.Printf("Diplay:%s\n", i.Data())
}
